<template>
  <div class="history-page">
    <div class="page-header">
      <el-button @click="$router.push('/')" type="primary" plain size="small">
        <el-icon><HomeFilled /></el-icon>
        返回首页
      </el-button>
    </div>

    <!-- 搜索和筛选区域 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" inline>
        <el-form-item label="平台">
          <el-select v-model="filterForm.platform" placeholder="选择平台">
            <el-option label="全部" value="" />
            <el-option label="小红书" value="xiaohongshu" />
            <el-option label="微信公众号" value="wechat" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="searchHistory">搜索</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 下载历史表格 -->
    <el-card class="history-table">
      <el-table :data="historyList" v-loading="loading">
        <el-table-column prop="platform" label="平台" width="100">
          <template #default="{ row }">
            <el-tag :type="row.platform === 'xiaohongshu' ? 'danger' : 'success'">
              {{ row.platform === 'xiaohongshu' ? '小红书' : '微信公众号' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
        
        <el-table-column prop="downloadTime" label="下载时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.downloadTime) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              size="small" 
              @click="viewDetail(row)"
              :disabled="row.status === 'failed'"
            >
              查看内容
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="deleteRecord(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      title="下载内容详情"
      width="60%"
      destroy-on-close
    >
      <div v-if="currentDetail">
        <h3>{{ currentDetail.title }}</h3>
        <div class="detail-content">
          <div class="text-content">{{ currentDetail.text }}</div>
          
          <!-- 图片预览 -->
          <div v-if="currentDetail.images?.length" class="image-list">
            <h4>图片内容</h4>
            <el-image
              v-for="(img, index) in currentDetail.images"
              :key="index"
              :src="img"
              :preview-src-list="currentDetail.images"
              fit="cover"
              class="preview-image"
            />
          </div>
          
          <!-- 视频预览 -->
          <div v-if="currentDetail.videos?.length" class="video-list">
            <h4>视频内容</h4>
            <video
              v-for="(video, index) in currentDetail.videos"
              :key="index"
              :src="video"
              controls
              class="preview-video"
            />
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import dayjs from 'dayjs'
import { DownloadHistory, DownloadDetail, StatusTypeMap, StatusTextMap } from '../types'
import { HomeFilled } from '@element-plus/icons-vue'

// 定义过滤表单
const filterForm = reactive({
  platform: '',
  dateRange: []
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 数据相关
const loading = ref(false)
const historyList = ref<DownloadHistory[]>([])
const detailVisible = ref(false)
const currentDetail = ref<DownloadDetail | null>(null)

// 初始化加载
onMounted(() => {
  loadHistoryData()
})

// 加载历史数据
async function loadHistoryData() {
  loading.value = true
  try {
    const response = await axios.get('/api/history', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value,
        platform: filterForm.platform,
        startDate: filterForm.dateRange?.[0],
        endDate: filterForm.dateRange?.[1]
      }
    })
    historyList.value = response.data.items
    total.value = response.data.total
  } catch (error) {
    ElMessage.error('获取历史记录失败')
  } finally {
    loading.value = false
  }
}

// 搜索历史
function searchHistory() {
  currentPage.value = 1
  loadHistoryData()
}

// 重置筛选
function resetFilter() {
  filterForm.platform = ''
  filterForm.dateRange = []
  searchHistory()
}

// 分页处理
function handleSizeChange(val: number) {
  pageSize.value = val
  loadHistoryData()
}

function handleCurrentChange(val: number) {
  currentPage.value = val
  loadHistoryData()
}

// 查看详情
async function viewDetail(row: any) {
  try {
    const response = await axios.get(`/api/history/detail/${row.id}`)
    currentDetail.value = response.data
    detailVisible.value = true
  } catch (error) {
    ElMessage.error('获取详情失败')
  }
}

// 删除记录
async function deleteRecord(id: number) {
  try {
    await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
      type: 'warning'
    })
    
    await axios.delete(`/api/history/${id}`)
    ElMessage.success('删除成功')
    loadHistoryData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 工具函数
function formatDate(date: string) {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

function getStatusType(status: string) {
  return StatusTypeMap[status] || 'info'
}

function getStatusText(status: string) {
  return StatusTextMap[status] || status
}
</script>

<style scoped>
.history-page {
  padding: 20px;
}

.page-header {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-icon {
  margin-right: 4px;
}

.filter-card {
  margin-bottom: 20px;
}

.history-table {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.detail-content {
  margin-top: 20px;
}

.text-content {
  white-space: pre-wrap;
  line-height: 1.6;
  color: #666;
}

.image-list, .video-list {
  margin-top: 20px;
}

.preview-image {
  width: 200px;
  height: 200px;
  margin: 10px;
  border-radius: 4px;
  cursor: pointer;
}

.preview-video {
  width: 100%;
  max-width: 500px;
  margin: 10px 0;
  border-radius: 4px;
}
</style> 